import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_app_info.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/widgets/common/xindong_text_field.dart';
import 'package:xindong/widgets/xindong_countdown_button.dart';

class XinDongCommonGetCodeView extends StatelessWidget {
  final FocusNode codeFocusNode = FocusNode();
  final Function(String code) onChange;

  XinDongCommonGetCodeView({super.key, required this.onChange});

  // 获取验证码事件
  void onGetCode() async {
    showLoading();
    var parameters = {
      "phone": XinDongUserController.to.userInfo?.phone ?? "",
      "device_id": XinDongAppDeviceInfo.instance.deviceUDID,
    };
    final object = await XinDongNetworking.instance.request(
      XinDongApi.codeGet,
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      codeFocusNode.requestFocus();
      XinDongCountdownButtonCtr.to.start();
    } else if (object.code == XinDongServerStatus.codeReuse) {
      // 使用上次验证码
      codeFocusNode.requestFocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: kCellHeight,
      color: DZColors.cellColor,
      padding: const EdgeInsets.only(left: kPaddingValue, right: kPaddingValue),
      child: Row(
        children: [
          const Text(
            "验证码",
            style: TextStyle(fontSize: 16, color: DZColors.titleColor, height: 1.3),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: XinDongTextField(
              hintText: "输入验证码",
              focusNode: codeFocusNode,
              onChanged: onChange,
              keyboardType: TextInputType.number,
              inputFormatters: [FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(4)],
              suffixIcon: XinDongCountdownButton(onTapSend: () => onGetCode()),
            ),
          ),
        ],
      ),
    );
  }
}
